package com.preguicoso.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.gson.Gson;
import com.preguicoso.server.dao.ItemCardapioDAO;
import com.preguicoso.server.entities.ItemCardapio;

public class ControllerServlet extends HttpServlet{

	private static final long serialVersionUID = -4926295173748093247L;


	@Override
	  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	      throws ServletException, IOException {
			PrintWriter out = resp.getWriter();
		try{
			String className = req.getParameter("class");
			String metodo = req.getParameter("method");
			String page = req.getParameter("page");
			String Npage = req.getParameter("nPage");
			
			int intPage = Integer.parseInt(page);
			int intNPage = Integer.parseInt(Npage);
			
			Class c = Class.forName("com.preguicoso.server.dao."+className+"DAO");
			Constructor ct = c.getConstructor();
			
			Object o = ct.newInstance();
            Method meth = c.getMethod(metodo);  
  
            List<? extends Object> retobj = (List<? extends Object>) meth.invoke(o); 
			List<JSONObject> listaJSON = new ArrayList<JSONObject>();
			
			JSONObject jo = new JSONObject();
	    	    jo.put("Quantidade", retobj.size());
	    	    jo.put("Page", intPage);
	    	    listaJSON.add(jo);
	    	    if(intNPage*(intPage+1)<retobj.size())
	    	    for (int i = intNPage*intPage; i < intNPage*(intPage+1); i++) {
	    	    		jo = new JSONObject(retobj.get(i));
		    	    listaJSON.add(jo);
			}
	    	    		
			JSONArray ja = new JSONArray(listaJSON);
			out.println(ja.toString());
            
		
		}catch (Exception e) {
			 out.println(" Ocorreu algum erro:" +e.getMessage()+e.getLocalizedMessage()+e.getStackTrace());
		}
	  }
}
